package com.itelite.controller;

import com.google.code.kaptcha.Producer;
import com.itelite.aop.WinControllerPointCut;
import com.itelite.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 26-06-2021-21:56
 **/
@RestController
@Slf4j
@Api("验证码模块")
public class CaptchaController {
    @Autowired
    private Producer producer;
    @Autowired
    private RedisService redisService;
    @GetMapping("/captcha.jpg")
    @ApiOperation("以jpg形式返回验证码图片")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置文本内容
        response.setContentType("image/jpeg");
        //创建验证码文本
        String capTxt = producer.createText();
        //将验证码文本设置到session中
        //将验证码存入redis中
        redisService.cacheValue(capTxt,capTxt,300);
        //创建验证码图片
        BufferedImage image = producer.createImage(capTxt);
        //获取响应输出流
        ServletOutputStream out = response.getOutputStream();
        //将验证码数据写到响应输出流中
        try (out) {
            ImageIO.write(image, "jpg", out);
            out.flush();
        }
    }
}
